package com.david.system.controller;

import com.david.common.comtext.UserContext;
import com.david.common.utils.JwtUtils;
import com.david.system.pojo.DTO.RePasswordDTO;
import com.david.system.pojo.DTO.UserLoginDTO;
import com.david.system.pojo.Entity.UserEntity;
import com.david.system.pojo.Entity.UserInfo;
import com.david.system.service.SysUserService;
import com.fasterxml.jackson.databind.node.ArrayNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import static com.david.common.utils.ResultUtils.fail;
import static com.david.common.utils.ResultUtils.success;

@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Slf4j
public class UserLoginController {
    private final AuthenticationManager authenticationManager;
    private final JwtUtils jwtUtils;
    private final SysUserService sysUserService;

    /**
    * @Description: 用户登录授权
    * @Param: [userLoginDTO]
    * @return: org.springframework.http.ResponseEntity<java.lang.Object>
    * @Author: david
    * @Date: 2024/5/28
    */
    @PostMapping("/login")
    public ResponseEntity<Object> doLogin(@RequestBody UserLoginDTO userLoginDTO) {
        try {
            UserEntity user = sysUserService.findByName(userLoginDTO.getUsername());
            if (user == null) {
                return fail(false,"用户名密码错误");
            }
            if (user.getStatus().equals("0")) {
                return fail(false, "账号停用，请联系管理员");
            }
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userLoginDTO.getUsername(), userLoginDTO.getPassword());
            Authentication authentication = authenticationManager.authenticate(auth);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            // 获取用户权限信息
            String authorityString = "";
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                authorityString = authority.getAuthority();
            }
            Map<String, Object> cliams = new HashMap<>();
            cliams.put("username", userDetails.getUsername());
            cliams.put("authorityString", authorityString);
            String jwtToken = jwtUtils.generateJwt(cliams);
            return success(true, jwtToken);
        } catch (Exception ex) {
//            return fail(false, ex.getMessage());
            return fail(false, "用户名密码错误");
        }
    }

    @GetMapping("/userInfo")
    public ResponseEntity<Object> getUserInfo(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        log.info("查询个人信息{}",username);
        UserInfo userInfo = sysUserService.getUserInfo(username);
        return success(true, userInfo);
        
    }

    /**
    * @Description: 用户修改密码
    * @Param: [rePasswordDTO]
    * @return: org.springframework.http.ResponseEntity<java.lang.Object>
    * @Author: david
    * @Date: 2024/5/28
    */
    @PostMapping("/repassword")
    public ResponseEntity<Object> changePassword(@RequestBody RePasswordDTO rePasswordDTO) {
        sysUserService.changePassword(rePasswordDTO);
        log.info("修改密码");
        return success(true, "密码修改成功");
    }


}
